package com.meida.module.product.provider.service.impl;

import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.utils.ApiAssert;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.JsonUtils;
import com.meida.module.product.client.entity.ProdMarketing;
import com.meida.module.product.client.entity.ProdProduct;
import com.meida.module.product.client.entity.ProdProductdetails;
import com.meida.module.product.client.entity.ProdTopic;
import com.meida.module.product.provider.mapper.ProdMarketingMapper;
import com.meida.module.product.provider.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品营销接口实现类
 *
 * @author flyme
 * @date 2019-12-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProdMarketingServiceImpl extends BaseServiceImpl<ProdMarketingMapper, ProdMarketing> implements ProdMarketingService {

    @Autowired
    private ProdProductService prodProductService;

    @Autowired
    private ProdProductdetailsService productdetailsService;

    @Autowired
    private ProdSkuService skuService;

    @Autowired
    private ProdTopicService topicService;
    @Autowired
    private ProdMarketingService marketingService;

    @Override
    public ResultBody beforePageList(CriteriaQuery<ProdMarketing> cq, ProdMarketing prodMarketing, EntityMap requestMap) {
        ApiAssert.isNotEmpty("marketingType不能为空", prodMarketing);
        //营销方式
        Integer marketingType = prodMarketing.getMarketingType();
        cq.select(ProdMarketing.class, "*");

        cq.eq("marketingType", marketingType);
        return ResultBody.ok();
    }

    /**
     * 根据商品ID查询
     *
     * @param productId
     * @return
     */
    @Override
    public ProdMarketing getByProductId(Long productId) {
        CriteriaQuery cq = new CriteriaQuery(ProdMarketing.class);
        cq.eq(true, "productId", productId);
        return getOne(cq);
    }

    /**
     * 批量添加营销商品
     *
     * @param productIds
     * @return
     */
    @Override
    public ResultBody batchAdd(Long[] productIds, Long topicId) {
        Boolean tag = false;
        List<ProdProduct> productList = prodProductService.selectByProductIds(productIds);
        if (FlymeUtils.isNotEmpty(productList)) {
            ProdTopic prodTopic = topicService.getById(topicId);
            if (FlymeUtils.isNotEmpty(prodTopic)) {
                List<ProdMarketing> marketingList = new ArrayList<>();
                for (ProdProduct product : productList) {
                    Long productId = product.getProductId();
                    ProdMarketing prodMarketing = marketingService.getByProductIdAndTopicId(productId, topicId);
                    ProdProductdetails prodProductdetails = productdetailsService.getById(productId);
                    if (FlymeUtils.isEmpty(prodMarketing)) {
                        ProdMarketing marketing = new ProdMarketing();
                        marketing.setProductId(product.getProductId());
                        marketing.setProductPrice(product.getProductPrice());
                        marketing.setProductImage(product.getCoverImage());
                        marketing.setProductTitle(product.getProductName());
                        marketing.setShopId(product.getShopId());
                        marketing.setPrivateSpce(prodProductdetails.getPrivateSpec());
                        marketing.setCompanyId(product.getCompanyId());
                        marketing.setSoldNum(0);
                        marketing.setLimitNum(1);
                        marketing.setTopicId(topicId);
                        marketing.setMarketingType(prodTopic.getTopicType());
                        marketing.setBeginTime(prodTopic.getBeginDate());
                        marketing.setEndTime(prodTopic.getEndDate());
                        marketing.setMarketingPrice(product.getProductPrice());
                        marketingList.add(marketing);
                    }
                }
                if (FlymeUtils.isNotEmpty(marketingList)) {
                    tag = marketingService.saveBatch(marketingList);
                }
            }
        }
        return ResultBody.result("添加", tag);
    }

    @Override
    public ProdMarketing getByProductIdAndTopicId(Long productId, Long topicId) {
        CriteriaQuery cq = new CriteriaQuery(ProdMarketing.class);
        cq.eq(true, "productId", productId);
        cq.eq(true, "topicId", topicId);
        return getOne(cq);
    }


    @Override
    public ResultBody findProductSkus(Long marketingId) {
        ApiAssert.isNotEmpty("产品ID不能为空", marketingId);
        ProdMarketing prodMarketing = getById(marketingId);
        ApiAssert.isNotEmpty("产品不存在", prodMarketing);
        //产品规格
        String json = prodMarketing.getPrivateSpce();
        EntityMap result = new EntityMap();
        //商品规格
        List<EntityMap> skusList = skuService.selectByProductId(prodMarketing.getProductId());
        for (EntityMap entityMap : skusList) {
            entityMap.put("price", prodMarketing.getMarketingPrice());
            String images = entityMap.get("images");
            if (FlymeUtils.isEmpty(images) || images.length() < 10) {
                images = prodMarketing.getProductImage();
                entityMap.put("images", images);
            }
        }
        List<EntityMap> skuDetails = new ArrayList<>();
        if (FlymeUtils.isNotEmpty(json)) {
            Map<String, Object> map = JsonUtils.jsonToMap(json, false);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String mapKey = entry.getKey();
                Object mapValue = entry.getValue();
                EntityMap m = new EntityMap();
                m.put("title", mapKey);
                m.put("value", mapValue);
                skuDetails.add(m);
            }
        }
        result.put("skuDetails", skuDetails);
        result.put("skusList", skusList);
        //限制购买数量
        result.put("limitNum", prodMarketing.getLimitNum());
        return ResultBody.ok(result);
    }

    @Override
    public List<Long> selectProductIds(Long topicId) {
        CriteriaQuery cq = new CriteriaQuery(ProdMarketing.class);
        cq.select("productId");
        cq.eq(true, "topicId", topicId);
        return listObjs(cq, e -> new Long(e.toString()));
    }

    /**
     * 更新营销商品
     * @param topicId
     * @return
     */
    public ResultBody updateByTopicId(Long topicId) {
        ProdTopic topic = topicService.getById(topicId);
        Boolean tag = false;
        if (FlymeUtils.isNotEmpty(topic)) {
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "marketingType", topic.getTopicType());
            cu.set(true, "beginTime", topic.getBeginDate());
            cu.set(true, "endTime", topic.getEndDate());
            cu.set(true, "marketingState", topic.getState());
            cu.eq(true, "topicId", topic.getTopicId());
            tag = update(cu);
        }
        return ResultBody.result("更新", tag);
    }

}
